<?php
namespace app\middleware;

class AllowCrossDomain
{

    
    public function handle($request, \Closure $next)
    {
        // 如果是预检请求（OPTIONS），提前响应
        if ($request->method() == 'OPTIONS') {
            return response('', 204)->header([
                'Access-Control-Allow-Origin'      => '*',  // 你也可以指定具体的域名
                'Access-Control-Allow-Methods'     => 'GET,POST,PUT,DELETE,OPTIONS',
                'Access-Control-Allow-Headers'     => 'Origin,Content-Type,Authorization,X-Requested-With,Token',
                'Access-Control-Allow-Credentials' => 'true',
            ]);
        }

        // 正常响应加上跨域头
        $response = $next($request);
        $response->header([
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'GET,POST,PUT,DELETE,OPTIONS',
            'Access-Control-Allow-Headers'     => 'Origin,Content-Type,Authorization,X-Requested-With,Token',
            'Access-Control-Allow-Credentials' => 'true',
        ]);

        return $response;
    }
}
